<template>
  <layout-table
    id="goodsListTable"
    ref="goodsListTableRef"
    class="goods-list-table"
    row-key="id"
    :url="props.tableUrl"
    :param="props.tableParam"
    :set-search="manullySearch"
    disable-auto-height
    @expand-change="handleExpandChange"
  >
    <slot name="expand">
      <el-table-column type="expand">
        <template #default="scope">
          <div
            v-expand-table-auto-resize="{parentTableSelector: '#goodsListTable' }"
            class="expand-table-wrapper"
            :style="{width: expandTableWidth}"
          >
            <product-list
              :loading="scope.row.productsLoading || false"
              :product-list="scope.row.products || []"
              :goods-row="scope.row"
              :edit-product-permission="editProductPermission"
              :delete-product-permission="deleteProductPermission"
              @click-edit="clickProductEdit"
              @click-delete="clickProductDelete"
            >
              <template #columns>
                <slot name="product-columns">
                  <product-id />
                  <product-name />
                  <product-thumbnail-url />
                  <product-original-price />
                  <product-sale-price />
                  <product-total-stock />
                  <product-stock />
                  <product-online-status />
                  <product-update-time />
                </slot>
                <el-button
                  link
                  type="primary"
                >
                  限购规则
                </el-button>
              </template>

              <template #product-rule="scope">
                <slot
                  name="product-rule-button"
                  :row="scope.row"
                />
              </template>
            </product-list>
          </div>
        </template>
      </el-table-column>
    </slot>

    <slot name="outer-columns">
      <goods-id />
      <goods-product-img />
      <goods-name />
      <goods-sell-count-stock />
    </slot>

    <el-table-column
      v-has="[
        ...editProductPermission,
        ...stockManagePermission,
        ...addProductPermission,
        ...deleteGoodsPermission]"
      label="操作"
      width="250"
      fixed="right"
    >
      <template #default="scope">
        <el-button
          v-has="editGoodsPermission"
          link
          type="primary"
          @click="clickEdit(scope.row)"
        >
          编辑
        </el-button>
        <el-button
          v-has="stockManagePermission"
          link
          type="primary"
          @click="clickStockManage(scope.row)"
        >
          调整库存
        </el-button>
        <el-button
          v-has="addProductPermission"
          link
          type="primary"
          @click="clickAddProduct(scope.row)"
        >
          新增规格
        </el-button>
        <el-button
          v-has="deleteGoodsPermission"
          link
          type="danger"
          @click="_deleteGoods(scope.row)"
        >
          删除
        </el-button>
        <slot
          name="goods-rule"
          :row="scope.row"
        />
      </template>
    </el-table-column>
  </layout-table>
</template>

<script setup lang="ts">
import { ElMessageBox } from "element-plus";
import { IGoodsPageRow, IStoreProductRow } from "@/api/modules/pointsMall";
import LayoutTable from "@/components/table/LayoutTable.vue";
import { request, post } from "@/utils/request";
import ApiResult from "@/api/base/ApiResult";

// 商品列表
import GoodsId from "@/components/goodsCenter/goodsListColumn/GoodsId.vue";
import GoodsProductImg from "@/components/goodsCenter/goodsListColumn/GoodsProductImg.vue";
import GoodsName from "@/components/goodsCenter/goodsListColumn/GoodsName.vue";
import GoodsSellCountStock from "@/components/goodsCenter/goodsListColumn/GoodsSellCountStock.vue";

// 规格列表
import ProductId from "@/components/goodsCenter/productListColumn/ProductId.vue";
import ProductName from "@/components/goodsCenter/productListColumn/ProductName.vue";
import ProductThumbnailUrl from "@/components/goodsCenter/productListColumn/ProductThumbnailUrl.vue";
import ProductOriginalPrice from "@/components/goodsCenter/productListColumn/ProductOriginalPrice.vue";
import ProductSalePrice from "@/components/goodsCenter/productListColumn/ProductSalePrice.vue";
import ProductTotalStock from "@/components/goodsCenter/productListColumn/ProductTotalStock.vue";
import ProductStock from "@/components/goodsCenter/productListColumn/ProductStock.vue";
import ProductOnlineStatus from "@/components/goodsCenter/productListColumn/ProductOnlineStatus.vue";
import ProductUpdateTime from "@/components/goodsCenter/productListColumn/ProductUpdateTime.vue";

const router = useRouter()
const store = useStore()
const props = withDefaults(defineProps<{
  tableUrl: string,
  tableParam: any,
  productListUrl: string,
  editGoodsPermission: string[],
  stockManagePermission: string[],
  addProductPermission: string[],
  deleteGoodsPermission: string[],
  editProductPermission: string[],
  deleteProductPermission: string[]
  deleteGoodsUrl?: string,
}>(), {
  tableUrl: '',
  tableParam: {},
  deleteGoodsUrl: '',
  editGoodsPermission: () => [],
  stockManagePermission: () => [],
  addProductPermission: () => [],
  deleteGoodsPermission: () => [],
  editProductPermission: () => [],
  deleteProductPermission: () => [],
})


const emits = defineEmits([
  'click-edit', // 编辑
  'click-delete', // 删除商品
  'click-stock-manage', // 调整库存
  'click-add-product', // 新增规格
  'click-product-edit', // 编辑规格
  'click-product-delete', // 删除规格
  'expand-change', // 展开子列表
])


const goodsListTableRef = ref<InstanceType<typeof LayoutTable> | null>(null)

const clickEdit = (row: IGoodsPageRow) => {
  console.log('点击了编辑商品', row)
  emits('click-edit', row)
}

const clickStockManage = (row: IGoodsPageRow) => {
  console.log('点击了库存调整')
  emits('click-stock-manage', row)
}

const clickAddProduct = (row: IGoodsPageRow) => {
  console.log('点击了添加规格')
  emits('click-add-product', row)
}

const clickProductEdit = (rowData: IGoodsPageRow, productRowData: IStoreProductRow) => {
  console.log('点击了规格表编辑', rowData, productRowData)
  emits('click-product-edit', rowData, productRowData)
}

const clickProductDelete = (row: IStoreProductRow, goodsRow: IGoodsPageRow) => {
  console.log('点击了规格表删除')
  emits('click-product-delete', row, goodsRow)
}

const _deleteGoods = async (row: IGoodsPageRow) => {
  console.log('点击了删除商品')
  if (props.deleteGoodsUrl) {
    const rs: ApiResult<any> = await request(props.deleteGoodsUrl, { id: row.id })
    if (rs.code === 200) {
      refreshList()
      ElMessage.success('删除成功')
    }
  } else {
    emits('click-delete', row)
  }
}

const manullySearch = ref(0)
const refreshList = () => {
  // goodsListTableRef.value?.research()
  ++manullySearch.value
}

const handleExpandChange = async (row: IGoodsPageRow, expandedRow: IGoodsPageRow) => {
  setExpandTableWidth()
  emits('expand-change', row, expandedRow)
}

const expandTableWidth = ref('0px')
const setExpandTableWidth = () => {
  const tableElement = document.querySelector('.goods-list-table')
  if (tableElement) {
    expandTableWidth.value = window.getComputedStyle(tableElement).getPropertyValue('width') // e.g. 1000px
  }
}

defineExpose({
  goodsListTableRef,
  refreshList
})
</script>

<style scoped lang="scss">
.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.row-img-wrapper {
  width: 100px;
  height: 100px;
}

.expand-table-wrapper {
  //padding: 20px;
}
</style>
